import { ProFormSelect } from '@ant-design/pro-components';
import { useEffect, useRef, useState } from 'react';
import { request } from '../../utils/request.ts';

const RemoteSelect = ({
  name,
  label,
  rules,
  placeholder = '请选择',
  fetchUrl,
  fetchMethod = 'POST',
  fetchParams = {},
  mapOption = (item) => ({ label: item.name, value: item.id }),
  pageSize = 10,
  ...restProps
}) => {
  const [options, setOptions] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const searchTimeout = useRef();

  // 拉取数据
  const fetchOptions = async (keyword = '', pageNum = 1) => {
    const params = {
      ...fetchParams,
      pageNum,
      pageSize,
    };
    if (keyword) {
      params.name = keyword;
    }
    const res = await request(fetchUrl, {
      method: fetchMethod,
      [fetchMethod === 'POST' ? 'data' : 'params']: params,
    });
    if (res.data) {
      const records = res.data.records || [];
      setTotal(res.data.total || 0);
      setPage(pageNum);
      setOptions(pageNum === 1
        ? records.map(mapOption)
        : [
          ...options,
          ...records.map(mapOption)
        ]
      );
    }
  };

  // 弹窗打开时加载第一页
  useEffect(() => {
    fetchOptions('', 1);
    // eslint-disable-next-line
  }, []);

  // 防抖搜索
  const handleSearch = (value) => {
    if (searchTimeout.current) {
      clearTimeout(searchTimeout.current);
    }
    searchTimeout.current = setTimeout(() => {
      fetchOptions(value, 1);
    }, 400);
  };

  return (
    <ProFormSelect
      name={name}
      label={label}
      rules={rules}
      showSearch
      debounceTime={300}
      options={options}
      fieldProps={{
        filterOption: false,
        onSearch: handleSearch,
        onPopupScroll: (e) => {
          const target = e.target;
          if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
            if (options.length < total) {
              fetchOptions('', page + 1);
            }
          }
        },
        placeholder,
        // 新增：透传 onChange
        onChange: (value, option) => {
          restProps.onChange && restProps.onChange(value, option);
        },
      }}
      {...restProps}
    />
  );
};

export default RemoteSelect;